package com.yanze.controller;

import com.yanze.pojo.User;
import com.yanze.pojo.request.RegisterUser;
import com.yanze.service.UserService;
import com.yanze.utils.BaseJSONResult;
import com.yanze.utils.C;
import org.n3r.idworker.Sid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    UserService mUserservice;

    @Autowired
    private Sid sid;

    /**
     * 注册
     * @param user String phone;String password;
     * @return 注册后用户对象
     */
    @RequestMapping(path = "/register", method = RequestMethod.POST)
    public BaseJSONResult register(@RequestBody() RegisterUser user) {
        //查看数据库中是否有相同的手机号，如果没有则添加；有则返回错误数据  方法：根据手机号查询数据库
        User exitUser = mUserservice.queryUserByPhone(user.getPhone());
        if (exitUser != null) {
            return BaseJSONResult.errorMsg("已存在该用户");
        }
        String userId = sid.nextShort();//获取随机Userid
        User dataUser = new User();
        dataUser.setUserid(userId);//id
        dataUser.setUsername(user.getPhone());//name
        dataUser.setNickname(user.getPhone());//nick
        dataUser.setUserphone(user.getPhone());//phone
        dataUser.setPassword(user.getPassword());//passwoad
        dataUser.setUsericon("/Header/b79cd3b0-c24b-47d1-88db-b3cd3257b3bd.jpg");//header
        dataUser.setTime(new Date());//time
        mUserservice.insertUser(dataUser);
        return BaseJSONResult.ok(dataUser);
    }

    /**
     * 登录
     *
     * @param phone    手机号
     * @param password 密码
     * @return 用户信息
     */
    @RequestMapping(path = "/login", method = RequestMethod.POST)
    public BaseJSONResult login(@RequestParam String phone, @RequestParam String password) {
        if (phone == null || password == null
                || phone.equals("") || password.equals("")) {
            return BaseJSONResult.errorMsg("参数不对");
        }
        //查看数据库中是否有相同的手机号，有则返回错误数据，没有也只提示不匹配，防止恶意操作  方法：根据手机号查询数据库
        User user = mUserservice.queryUserByPhone(phone);
        if (user != null && phone.equals(user.getUserphone()) && password.equals(user.getPassword())) {
            return BaseJSONResult.ok(user);
        }
        return BaseJSONResult.errorMsg("用户名与密码不匹配");
    }

    /**
     * 根据Userid查询用户信息
     */
    @RequestMapping(path = "/getUserInfoById", method = RequestMethod.GET)
    public BaseJSONResult getUserInfoById(@RequestParam("userid") String userid) {
        if (userid == null || userid.equals("")) {
            return BaseJSONResult.errorMsg("参数错误");
        }
        User user = mUserservice.queryUserById(userid);
        return BaseJSONResult.ok(user);
    }

    /**
     * 修改用户信息
     *
     * @return 成功或失败
     */
    @RequestMapping(path = "/modifyUserInfo", method = RequestMethod.POST)
    public BaseJSONResult modifyUserInfo(@RequestParam String userid,
                                         @RequestParam(defaultValue = "") String nickname,
                                         @RequestParam(defaultValue = "") String userqq,
                                         @RequestParam(defaultValue = "") String userwechat) {
        User exitUser = mUserservice.queryUserById(userid);
        if (exitUser == null) {
            return BaseJSONResult.errorMsg("查无此用户，请重新登录");
        }
        int successCount = 0;
        if (nickname != null && !nickname.equals("")) {
            exitUser.setNickname(nickname);
            successCount = mUserservice.updateUser(exitUser);
        } else if (userqq != null && !userqq.equals("")) {
            exitUser.setUserqq(userqq);
            successCount = mUserservice.updateUser(exitUser);
        } else if (userwechat != null && !userwechat.equals("")) {
            exitUser.setUserwechat(userwechat);
            successCount = mUserservice.updateUser(exitUser);
        } else {
            return BaseJSONResult.errorMsg("无可修改信息");
        }
        if (successCount > 0) {    //成功修改的个数
            return BaseJSONResult.ok(exitUser);
        } else {
            return BaseJSONResult.ok();
        }
    }

    /**
     * 修改头像
     */
    @RequestMapping(path = "/uploadHeader", method = RequestMethod.POST)
    public BaseJSONResult uploadHeader(@RequestParam(defaultValue = "") String userid, @RequestParam("file") MultipartFile file) {
        if ("".equals(userid)) {
            return BaseJSONResult.errorMsg("参数错误");
        }
        User exitUser = mUserservice.queryUserById(userid);
        if (exitUser == null) {
            return BaseJSONResult.errorMsg("查无此用户");
        }
        if (!file.isEmpty()) {
            String originalFilename = file.getOriginalFilename();
            String headerPath = C.path.IMG_HEADER + UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
            String targetPath = C.path.IMG_PATH + headerPath;
            try {
                File targetfile = new File(targetPath);
                if (!targetfile.exists()) {
                    targetfile.createNewFile();
                }
                file.transferTo(targetfile);//保存图片至指定路径
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                return BaseJSONResult.errorMsg("上传失败," + e.getMessage());
            } catch (IOException e) {
                e.printStackTrace();
                return BaseJSONResult.errorMsg("上传失败," + e.getMessage());
            }
            //保存成功，更新数据库中User图片路径
            exitUser.setUsericon(headerPath);
            int flag = mUserservice.updateUser(exitUser);
            System.out.println("上传成功,真实路径是： " + targetPath + " 网络路径是：" + headerPath);
            if (flag > 0) {
                // TODO: 2018/5/4 删除原来存在的图片
                return BaseJSONResult.ok(exitUser);
            } else {
                return BaseJSONResult.ok();
            }
        } else {
            return BaseJSONResult.errorMsg("上传失败，因为文件是空的.");
        }
    }

}
